package com.zhuangfei.hos_timetableview.ability;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.zhuangfei.hos_timetableview.ResourceTable;
import com.zhuangfei.hos_timetableview.model.MySubject;
import com.zhuangfei.hos_timetableview.model.SubjectRepertory;
import com.zhuangfei.hos_timetableview.utils.ToastUtil;
import com.zhuangfei.timetable.TimetableView;
import com.zhuangfei.timetable.listener.ISchedule;
import com.zhuangfei.timetable.listener.IWeekView;
import com.zhuangfei.timetable.listener.OnItemBuildAdapter;
import com.zhuangfei.timetable.model.Schedule;
import com.zhuangfei.timetable.utils.ElementUtil;
import com.zhuangfei.timetable.view.WeekView;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.StackLayout;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;

import java.util.ArrayList;
import java.util.List;

public class SimpleAbility extends Ability implements Component.ClickedListener {
    public static final String AD_URL = "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png";

    // 控件
    TimetableView mTimetableView;
    WeekView mWeekView;

    DirectionalLayout layout;
    Text titleTextView;
    List<MySubject> mySubjects;

    // 记录切换的周次，不一定是当前周
    int target = -1;
    LoadingPopupView alertDialog;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_base_func);
        // 添加表头的include
        StackLayout stInclude = (StackLayout) findComponentById(ResourceTable.Id_st_include);
        stInclude.addComponent(LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_header_base_func, stInclude, false));

        titleTextView = (Text) findComponentById(ResourceTable.Id_id_title);
        layout = (DirectionalLayout) findComponentById(ResourceTable.Id_id_layout);
        layout.setClickedListener(this);
        initTimetableView();

        requestData();
    }

    /**
     * 2秒后刷新界面，模拟网络请求
     */
    private void requestData() {
        alertDialog = (LoadingPopupView) new XPopup.Builder(getContext())
                .dismissOnBackPressed(false)
                .asLoading("模拟请求网络中..").show();
        handler.sendEvent(0x123, 1000);
    }

    EventHandler handler = new EventHandler(EventRunner.getMainEventRunner()) {
        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (alertDialog != null) {
                alertDialog.dismiss();
            }
            mySubjects = SubjectRepertory.loadDefaultSubjects();
            // 增加广告
            MySubject adSubject = new MySubject();
            adSubject.setName("【广告】");
            adSubject.setStart(1);
            adSubject.setStep(2);
            adSubject.setDay(7);
            List<Integer> list = new ArrayList<>();
            for (int i = 1; i <= 20; i++) {
                list.add(i);
            }
            adSubject.setWeekList(list);
            adSubject.setUrl(AD_URL);
            mySubjects.add(adSubject);

            mWeekView.source(mySubjects).showView();
            mTimetableView.source(mySubjects).showView();
        }
    };

    /**
     * 初始化课程控件
     */
    private void initTimetableView() {
        // 获取控件
        mWeekView = (WeekView) findComponentById(ResourceTable.Id_id_weekview);
        mTimetableView = (TimetableView) findComponentById(ResourceTable.Id_id_timetableView);

        // 设置周次选择属性
        mWeekView.curWeek(1)
                .callback(new IWeekView.OnWeekItemClickedListener() {
                    @Override
                    public void onWeekClicked(int week) {
                        int cur = mTimetableView.curWeek();
                        // 更新切换后的日期，从当前周cur->切换的周week
                        mTimetableView.onDateBuildListener()
                                .onUpdateDate(cur, week);
                        mTimetableView.changeWeekOnly(week);
                    }
                })
                .callback(new IWeekView.OnWeekLeftClickedListener() {
                    @Override
                    public void onWeekLeftClicked() {
                        onWeekLeftLayoutClicked();
                    }
                })
                .isShow(false) // 设置隐藏，默认显示
                .showView();

        mTimetableView.curWeek(1)
                .curTerm("大三下学期")
                .callback(new ISchedule.OnItemClickListener() {
                    @Override
                    public void onItemClick(Component component, List<Schedule> scheduleList) {
                        display(scheduleList);
                    }
                })
                .callback(new ISchedule.OnItemLongClickListener() {
                    @Override
                    public void onLongClick(Component component, int day, int start) {
                        ToastUtil.showToast(SimpleAbility.this, "长按:周" + day + ",第" + start + "节");
                    }
                })
                .callback(new ISchedule.OnWeekChangedListener() {
                    @Override
                    public void onWeekChanged(int curWeek) {
                        titleTextView.setText("第" + curWeek + "周");
                    }
                })
                .callback(new OnItemBuildAdapter() {
                    @Override
                    public void onItemUpdate(StackLayout layout, Text textView, Text countTextView, Schedule schedule, ShapeElement gd) {
                        super.onItemUpdate(layout, textView, countTextView, schedule, gd);
                        if (schedule.getName().equals("【广告】")) {
                            layout.removeAllComponents();
                            Image imageView = new Image(SimpleAbility.this);
                            imageView.setLayoutConfig(new StackLayout.LayoutConfig(StackLayout.LayoutConfig.MATCH_PARENT, StackLayout.LayoutConfig.MATCH_PARENT));
                            layout.addComponent(imageView);
                            String url = (String) schedule.getExtras().get(MySubject.EXTRAS_AD_URL);
                            getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
                                @Override
                                public void run() {
                                    Glide.with(SimpleAbility.this)
                                            .load(url)
                                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                                            .into(imageView);
                                }
                            });
                            imageView.setClickedListener(new Component.ClickedListener() {
                                @Override
                                public void onClick(Component component) {
                                    ToastUtil.showToast(SimpleAbility.this, "进入广告网页链接");
                                }
                            });
                        }
                    }
                })
                .showView();
    }

    /**
     * 更新一下，防止因程序在后台时间过长（超过一天）而导致的日期或高亮不准确问题。
     *
     * @param intent 意图
     */
    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
        mTimetableView.onDateBuildListener().onHighLight();
    }

    /**
     * 周次选择布局的左侧被点击时回调<br/>
     * 对话框修改当前周次
     */
    protected void onWeekLeftLayoutClicked() {
        final String[] items = new String[20];
        int itemCount = mWeekView.itemCount();
        for (int i = 0; i < itemCount; i++) {
            items[i] = "第" + (i + 1) + "周";
        }
        target = -1;
        new XPopup.Builder(getContext())
                .isDarkTheme(true)
                .asCenterList("设置当前周", items,
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                target = position;
                                if (target != -1) {
                                    mWeekView.curWeek(target + 1).updateView();
                                    mTimetableView.changeWeekForce(target + 1);
                                }
                            }
                        })
                .show();
    }

    /**
     * 显示内容
     *
     * @param beans 数据源
     */
    protected void display(List<Schedule> beans) {
        String str = "";
        for (Schedule bean : beans) {
            str += bean.getName() + "," + bean.getWeekList().toString() + "," + bean.getStart() + "," + bean.getStep() + "\n";
        }
        ToastUtil.showToast(this, str);
    }

    @Override
    public void onClick(Component component) {
        if (component.getId() == ResourceTable.Id_id_layout) {
            // 如果周次选择已经显示了，那么将它隐藏，更新课程、日期
            // 否则，显示
            if (mWeekView.isShowing()) {
                hideWeekView();
            } else {
                showWeekView();
            }
        }
    }

    /**
     * 隐藏周次选择，此时需要将课表的日期恢复到本周并将课表切换到当前周
     */
    public void hideWeekView() {
        mWeekView.isShow(false);
        titleTextView.setTextColor(new Color(ElementUtil.getColor(this, com.zhuangfei.timetable.ResourceTable.Color_app_course_textcolor_blue)));
        int cur = mTimetableView.curWeek();
        mTimetableView.onDateBuildListener()
                .onUpdateDate(cur, cur);
        mTimetableView.changeWeekOnly(cur);
    }

    public void showWeekView() {
        mWeekView.isShow(true);
        titleTextView.setTextColor(new Color(ElementUtil.getColor(this, com.zhuangfei.timetable.ResourceTable.Color_app_red)));
    }

}
